const multer = require("koa-multer");
const fs = require("fs");
const path = require("path");
const config = require("../config");

//文件保存路径
function destination(path = "temp") {
  return "public/" + path;
}

//修改文件名称 扩展
function filename(file) {
  let extension = file ? file.name.split(".").pop() : "jpeg";
  return Date.now() + "." + extension;
}

//文件上传
var uploadFile = (ctx, fileName) => {
  let file = ctx.request.files.file;
  if (!fileName && file) {
    fileName = filename(file);
    console.log("文件名字————", fileName);
    // 创建可读流
    let render = fs.createReadStream(file.path);
    let fileDir = destination("uploads/");
    let filePath = fileDir + fileName;
    if (!fs.existsSync(fileDir)) {
      fs.mkdirSync(fileDir, err => {
        console.log(err);
        console.log("创建失败");
        ctx.body = { msg: err };
      });
    } else {
      // 创建写入流
      let upStream = fs.createWriteStream(filePath);
      render.pipe(upStream);
      ctx.body = { fileLink: "http://localhost:3000/uploads/" + fileName };
    }
  } else {
    ctx.body = { msg: "请选择正确的文件" };
  }
};

// 导出配置
module.exports = {
  config: multer(),
  uploadFile: uploadFile
};
